package com.koron.css2.clientCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.BankBean;
import com.koron.css2.baseConfig.bean.BusinessAbodeBean;
import com.koron.css2.baseConfig.bean.PrefStrategyBean;
import com.koron.css2.baseConfig.bean.TradeClassifyBean;
import com.koron.css2.baseConfig.mapper.*;
import com.koron.css2.baseConfig.queryBean.BaseBookQueryBean;
import com.koron.css2.baseConfig.vo.BaseBookListVO;
import com.koron.css2.clientCenter.bean.*;
import com.koron.css2.clientCenter.mapper.AccountInfoMapper;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.meterService.MeterService;
import com.koron.css2.meterService.dto.MsInfoDto;
import com.koron.css2.serviceManage.bean.DistrictBean;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.DistrictMapper;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.util.CollectionUtils;
import org.swan.bean.MessageBean;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户详情接口
 *
 * @author 甄玉晴
 *
 */
public class UserInfoQuery implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		try {
			MessageBean<UserDetailInfoBean> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功",
					UserDetailInfoBean.class);
			UserBean userBean = JsonUtils.objectToPojo(req.getData(), UserBean.class);
			UserDetailInfoBean userDetailInfo = getUserDetailInfoByUserNo(factory, userBean.getUserNo(), userInfo);
			if(userDetailInfo==null) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败，找不到该用户编号", null);
			}

			info.setData(userDetailInfo);
			return info;
		} catch (Exception e) {
			logger.error("客户管理列表查询失败", e);
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败", null);
		}
	}

	public UserDetailInfoBean getUserDetailInfoByUser(SessionFactory factory, UserBean user, UserInfoBean userInfo) throws Exception {
		AccountInfoMapper accountMapper = factory.getMapper(AccountInfoMapper.class);
		CtmInfoMapper ctmMapper = factory.getMapper(CtmInfoMapper.class);
		BaseBookMapper bookMapper = factory.getMapper(BaseBookMapper.class);
		List<BaseBookListVO> books = bookMapper.select(new BaseBookQueryBean());

		if(user != null && StringUtils.isNotBlank(user.getBookNo())) {
			if (books != null && books.size() > 0) {
				String meterReadingStaff = "";
				meterReadingStaff = books.stream().filter(t -> t.getBookNo().equals(user.getBookNo())).findFirst()
						.orElse(new BaseBookListVO()).getMeterReadingStaffName();
				if(meterReadingStaff != null)
					user.setMeterReadingStaff(meterReadingStaff);
			}
		}

		AccountInfoBean accountInfo = accountMapper.getAccountInfoByCode(user.getAccountNo(), AccountInfoBean.ACCOUNT);// 获取账户信息
		CtmInfoBean ctmInfo = ctmMapper.getCtmInfoByCtmNo(user.getCtmNo(), CtmInfoBean.CTM);// 获取客服信息
		// 获取水表信息
		MsInfoDto msInfo=null;
		if (!StringUtils.isEmpty(user.getMeterNo())) {
			MeterService meterSrvice = new MeterService();
			msInfo = ADOConnection.runTask("_default", meterSrvice, "getMsInfoByNo", MsInfoDto.class,
					user.getMeterNo(),userInfo.getCurWaterCode());
		}
		if(StringUtils.isNotBlank(accountInfo.getVatFlag()) && "1".equals(accountInfo.getVatFlag())) {
			accountInfo.setVatFlagName("是");
		}else {
			accountInfo.setVatFlagName("否");
		}
		// 获取数据字典信息
		if (StringUtils.isNotBlank(user.getStatus())) {
			user.setStatusName(Tools.getDicNameByCodeAndValue(factory, "CUS", user.getStatus()));
		}
		if (StringUtils.isNotBlank(ctmInfo.getCertType())) {
			ctmInfo.setCertTypeName(Tools.getDicNameByCodeAndValue(factory, "IDT", ctmInfo.getCertType()));
		}
        if (StringUtils.isNotBlank(user.getValveStatus())){
            user.setValveStatusName(Tools.getDicNameByCodeAndValue(factory,"MVS",user.getValveStatus()));
        }
		if (StringUtils.isNotBlank(user.getMeterReadingCycle())) {
            List<ReadCycleConfigBean> readCycleConfigBeans = factory.getMapper(UserInfoMapper.class).readCycleConfigList();
            if(CollectionUtils.isEmpty(readCycleConfigBeans)){
                logger.error("执行UserInfoQuery readCycleConfigList-获取抄表周期配置类数据失败!");
                throw new Exception("抄表周期配置类数据为空!");
            }
            Map<String, String> readCycleConfigMap = readCycleConfigBeans.stream()
                    .collect(Collectors.toMap(x -> x.getId(), x -> x.getName()));
            user.setMeterReadingCycleName(readCycleConfigMap.get(user.getMeterReadingCycle()));
		}
		if (StringUtils.isNotBlank(user.getSetupMeterLocation())) {
			user.setSetupMeterLocationName(Tools.getDicNameByCodeAndValue(factory, "CTL", user.getSetupMeterLocation()));
		}
		if (StringUtils.isNotBlank(user.getUseWaterObject())) {
			user.setUseWaterObjectName(Tools.getDicNameByCodeAndValue(factory, "UWS", user.getUseWaterObject()));
		}
		if (StringUtils.isNotBlank(user.getMeterBjwz())) {
			user.setMeterBjwzName(Tools.getDicNameByCodeAndValue(factory, "BJWZ", user.getMeterBjwz()));
		}
		if (StringUtils.isNotBlank(user.getMeterBjxs())) {
			user.setMeterBjxsName(Tools.getDicNameByCodeAndValue(factory, "BJXS", user.getMeterBjxs()));
		}
		if (StringUtils.isNotBlank(user.getMeterUse())) {
			user.setMeterUseName(Tools.getDicNameByCodeAndValue(factory, "CMC", user.getMeterUse()));
		}
		if (StringUtils.isNotBlank(user.getMeterType())) {
			user.setMeterTypeName(Tools.getDicNameByCodeAndValue(factory, "MMT", user.getMeterType()));
		}
		if (accountInfo != null && StringUtils.isNotBlank(accountInfo.getAccountType())) {
			accountInfo.setAccountTypeName(Tools.getDicNameByCodeAndValue(factory, "ACT", accountInfo.getAccountType()));
		}
		if (accountInfo != null && StringUtils.isNotBlank(accountInfo.getPayWay())) {
			accountInfo.setPayWayName(Tools.getDicNameByCodeAndValue(factory, "BPW", accountInfo.getPayWay()));
		}
		if (accountInfo != null && StringUtils.isNotBlank(accountInfo.getInvoiceType())) {
			accountInfo.setInvoiceTypeName(Tools.getDicNameByCodeAndValue(factory, "BBT", accountInfo.getInvoiceType()));
		}
		if (accountInfo != null && StringUtils.isNotBlank(accountInfo.getDeliverWay())) {
			accountInfo.setDeliverWayName(Tools.getDicNameByCodeAndValue(factory, "SDW", accountInfo.getDeliverWay()));
		}
		if (StringUtils.isNotBlank(ctmInfo.getCtmType())) {
			ctmInfo.setCtmTypeName(Tools.getDicNameByCodeAndValue(factory, "CTT", ctmInfo.getCtmType()));
		}
		if (StringUtils.isNotBlank(ctmInfo.getCreditLevel())) {
			ctmInfo.setCreditLevelName(Tools.getDicNameByCodeAndValue(factory, "CDL", ctmInfo.getCreditLevel()));
		}
		if (StringUtils.isNotBlank(user.getSplitMeterWay())) {
			user.setSplitMeterWayName(Tools.getDicNameByCodeAndValue(factory, "MRM", user.getSplitMeterWay()));
		}
		if (StringUtils.isNotBlank(user.getMeterBjwz())) {
			user.setMeterBjwzName(Tools.getDicNameByCodeAndValue(factory, "BJWZ", user.getMeterBjwz()));
		}
		if (StringUtils.isNotBlank(user.getMeterBjxs())) {
			user.setMeterBjxsName(Tools.getDicNameByCodeAndValue(factory, "BJXS", user.getMeterBjxs()));
		}
		/*
		if (StringUtils.isNotBlank(user.getMeterSite())) {
			user.setMeterSite(Tools.getDicNameByCodeAndValue(factory, "BW", user.getMeterSite()));
		}*/
		// 获取营业所名称
		if (!StringUtils.isBlank(user.getBusinessAbode())) {
			BusinessAbodeMapper busniessAbodemapper = factory.getMapper(BusinessAbodeMapper.class);
			BusinessAbodeBean abode = busniessAbodemapper.findBusinessAbodeById(user.getBusinessAbode());
			user.setBusinessAbodeName(abode==null?"":abode.getAbodeName());
		}
		// 获取营业区域
		if (!StringUtils.isBlank(user.getBusinessArea())) {
			BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);
			user.setBusinessAreaName(
					businessAreaMapper.findBusinessAreaById(user.getBusinessArea(), userInfo.getCurWaterCode()));
		}
		// 获取行政区域
		if (!StringUtils.isBlank(user.getAdminArea())) {
			DistrictMapper districtMapper = factory.getMapper(DistrictMapper.class);
			DistrictBean district = districtMapper.findDistrictById(user.getAdminArea());
			user.setAdminAreaName(district==null?"":district.getSname());
		}
		// 获取行业分类名称
		if (!StringUtils.isBlank(user.getTradeClassify())) {
			TradeClassifyMapper tradeMapper = factory.getMapper(TradeClassifyMapper.class);
			TradeClassifyBean trade = tradeMapper.selectTradeClassifyById(user.getTradeClassify());
			user.setTradeClassifyName(trade==null?"":trade.getTradeName());
		}
		// 获取优惠策略名称
		if (!StringUtils.isBlank(user.getPrefStrategyId())) {
			PrefStrategyMapper prefStrategyMapper = factory.getMapper(PrefStrategyMapper.class);
			PrefStrategyBean prefStrategy = prefStrategyMapper.selectPrefStrategyById(user.getPrefStrategyId());
			user.setPrefStrategyName(prefStrategy==null?"":prefStrategy.getStrategyName());
		}
//		// 获取用水类型
//		if (!StringUtils.isBlank(user.getUseWaterType())) {
//			WaterTypeMapper waterTypeMapper = factory.getMapper(WaterTypeMapper.class);
//			WaterTypeBean waterType = waterTypeMapper.findWaterTypeById(user.getUseWaterType());
//			user.setUseWaterTypeName(waterType==null?"":waterType.getWaterTypeName());
//		}
		BankMapper bankeMapper = factory.getMapper(BankMapper.class);
		// 获取开户行名称
		if (!StringUtils.isBlank(accountInfo.getOpenAccountBank())) {
			BankBean banke = bankeMapper.findBankById(accountInfo.getOpenAccountBank());
			accountInfo.setOpenAccountBankName(banke==null?accountInfo.getOpenAccountBank():banke.getBankName());
		}
		// 获取购买方开户行名称
		if (!StringUtils.isBlank(accountInfo.getInvoiceBank())) {
			BankBean banke = bankeMapper.findBankById(accountInfo.getInvoiceBank());
			accountInfo.setInvoiceBankName(banke==null?accountInfo.getInvoiceBank():banke.getBankName());
		}
		UserDetailInfoBean bean = new UserDetailInfoBean();
		bean.setUserInfo(user);
		bean.setAccountInfo(accountInfo);
		bean.setCtmInfo(ctmInfo);
		bean.setMsInfo(msInfo);
		return bean;
	}

	public UserDetailInfoBean getUserDetailInfoByUserNo(SessionFactory factory, String userNo, UserInfoBean userInfo) throws Exception {
		UserInfoMapper mapper = factory.getMapper(UserInfoMapper.class);
		UserBean user = mapper.getUserInfoByUserNo(userNo, UserBean.USER);// 获取用户信息
		if(user==null) {
			return null;
		}
		return getUserDetailInfoByUser(factory, user, userInfo);
	}

}
